#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTcpSocket>
#include <QMessageBox>
#include <QMap>
#include "tools.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //创建服务器对象
    tcpServer = new QTcpServer(this);

    // 连接信号和槽
    connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::onNewConnection);

    if (!tcpServer->listen(QHostAddress::Any, 8090)) {
        qCritical() << "服务器启动失败!";
    } else {
        qDebug() << "服务器开始监听8090端口!";
    }

}

MainWindow::~MainWindow()
{
    delete ui;
}


//处理新连接槽函数
void MainWindow::onNewConnection()
{
    // 获取新连接
    QTcpSocket *clientSocket = tcpServer->nextPendingConnection();

    // 连接 readyRead 信号以处理接收的数据
    connect(clientSocket, &QTcpSocket::readyRead, this, &MainWindow::onDataReceived);

    qDebug() << "有客户端连接!";
}

//处理数据传输槽函数
void MainWindow::onDataReceived()
{
    //等待0.2s
    waitForTimeout(200);
    // 获取客户端发送的数据
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket *>(sender());
    QByteArray data = clientSocket->readAll();
    qDebug() << "接收到数据 ";

    //数据处理
    quint8 packetType = data[0];

    //qDebug() << "packetType ="<<packetType;

    if(packetType == Database){
        //处理数据库类型包
        processDatabase(data,clientSocket);


    }else if(packetType == ChatData){
        //聊天数据类型的包
    }
}


